<template>
	<view class="content">
		<view class="msg">
			{{JSON.stringify(datas) === '[]' ? '':datas.join('...')}}
		</view>

		<view class="control">
			<view @click="control('s')" class="btns stop">
				停止
			</view>
			<view @touchstart="control('lf')" @touchend="control('s')" class="btns lup">
				左前
			</view>
			<view @touchstart="control('f')" @touchend="control('s')" class="btns up">
				前进
			</view>
			<view @touchstart="control('rf')" @touchend="control('s')" class="btns rup">
				右前
			</view>
			<view @touchstart="control('r')" @touchend="control('s')" class="btns right">
				右移
			</view>
			<view @touchstart="control('rb')" @touchend="control('s')" class="btns rdown">
				右退
			</view>
			<view @touchstart="control('b')" @touchend="control('s')" class="btns down">
				退后
			</view>
			<view @touchstart="control('lb')" @touchend="control('s')" class="btns ldown">
				左退
			</view>
			<view @touchstart="control('l')" @touchend="control('s')" class="btns left">
				左移
			</view>
		</view>
		<view class="control">
			<view @click="control('s')" class="btns stop">
				停止
			</view>
			<view @touchstart="control('lt')" @touchend="control('s')" class="btns lup">
				左转圈
			</view>
			<view @touchstart="control('rt')" @touchend="control('s')" class="btns rup">
				右转圈
			</view>
			<view @touchstart="control('fcl')" @touchend="control('s')" class="btns left">
				前中左
			</view>
			<view @touchstart="control('fcr')" @touchend="control('s')" class="btns right">
				前中右
			</view>
			<view @touchstart="control('bcr')" @touchend="control('s')" class="btns rdown">
				后中右
			</view>
			<view @touchstart="control('bcl')" @touchend="control('s')" class="btns ldown">
				后中左
			</view>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				writeuuid: '',
				notifyuuid: '',
				deviceId: '',
				serviceId: '',
				datas: [],
			}
		},
		onShow() {
			const thit = this;
			this.serviceId = uni.getStorageSync('serviceId');
			this.deviceId = uni.getStorageSync('deviceId')
			const list = uni.getStorageSync('characteristics');
			list.map((item) => {
				if (item['type'] === 'write') {
					thit.writeuuid = item['uuid']
				}
				if (item['type'] === 'notify') {
					thit.notifyuuid = item['uuid']
				}
			})
			this.notifyBLECharacteristicValueChange()
		},
		methods: {
			notifyBLECharacteristicValueChange() {
				const thit = this;
				setTimeout(() => {
					uni.notifyBLECharacteristicValueChange({
						state: true, // 启用 notify 功能
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: thit.deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: thit.serviceId,
						// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
						characteristicId: thit.notifyuuid,
						success: (res) => {
							console.log('notifyBLECharacteristicValueChange success', res.errMsg)
							thit.onValueChang()
						},
						fail: (res) => {
							console.log('notifyBLECharacteristicValueChange success2', res.errMsg)
						}
					})
				}, 1000)
			},
			onValueChang() {
				const thit = this
				uni.onBLECharacteristicValueChange((res) => {
					console.log('characteristic value comed: 调整变化监听', res)
					thit.datas.unshift(thit.arrayBufferToString(res.value));
				})
			},
			stringToArrayBuffer(str) {
				var bytes = new Array();
				var len, c;
				len = str.length;
				for (var i = 0; i < len; i++) {
					c = str.charCodeAt(i);
					if (c >= 0x010000 && c <= 0x10FFFF) {
						bytes.push(((c >> 18) & 0x07) | 0xF0);
						bytes.push(((c >> 12) & 0x3F) | 0x80);
						bytes.push(((c >> 6) & 0x3F) | 0x80);
						bytes.push((c & 0x3F) | 0x80);
					} else if (c >= 0x000800 && c <= 0x00FFFF) {
						bytes.push(((c >> 12) & 0x0F) | 0xE0);
						bytes.push(((c >> 6) & 0x3F) | 0x80);
						bytes.push((c & 0x3F) | 0x80);
					} else if (c >= 0x000080 && c <= 0x0007FF) {
						bytes.push(((c >> 6) & 0x1F) | 0xC0);
						bytes.push((c & 0x3F) | 0x80);
					} else {
						bytes.push(c & 0xFF);
					}
				}
				var array = new Int8Array(bytes.length);
				for (var i in bytes) {
					array[i] = bytes[i];
				}
				return array.buffer;
			},
			arrayBufferToString(arr) {
				if (typeof arr === 'string') {
					return arr;
				}
				var dataview = new DataView(arr);
				var ints = new Uint8Array(arr.byteLength);
				for (var i = 0; i < ints.length; i++) {
					ints[i] = dataview.getUint8(i);
				}
				arr = ints;
				var str = '',
					_arr = arr;
				for (var i = 0; i < _arr.length; i++) {
					var one = _arr[i].toString(2),
						v = one.match(/^1+?(?=0)/);
					if (v && one.length == 8) {
						var bytesLength = v[0].length;
						var store = _arr[i].toString(2).slice(7 - bytesLength);
						for (var st = 1; st < bytesLength; st++) {
							store += _arr[st + i].toString(2).slice(2);
						}
						str += String.fromCharCode(parseInt(store, 2));
						i += bytesLength - 1;
					} else {
						str += String.fromCharCode(_arr[i]);
					}
				}
				return str;
			},
			control(val) {
				// 转换成ArrayBuffer类型
				const thit = this
				const buff = this.stringToArrayBuffer(val);
				const buffer = buff
				uni.writeBLECharacteristicValue({
					// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: thit.deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: thit.serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId: thit.writeuuid,
					// 这里的value是ArrayBuffer类型
					value: buffer,
					success(res) {
						console.log("写入成功");
					},
					fail(res) {
						console.log("写入失败", res)
						uni.showToast({
							icon: 'none',
							title: '下发失败'
						});
					}
				})
			}
		}
	}
</script>

<style>
	.msg {
		transform: rotate(90deg);
		overflow-x: hidden;
		overflow-y: scroll;
		position: absolute;
		top: 30%;
		left: 40%;
		width: 90%;
		height: 50px;
		margin: 0 auto;
	}

	.content {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-around;
		background: #0f3854;
		background: radial-gradient(ellipse at center, #0a2e38 0%, #000000 70%);
		width: 100%;
		height: 100%;
		/* z-index: 1; */
		position: fixed;
	}

	.control {
		width: 40%;
		/* transform: rotate(90deg); */
		/* margin-top: 100px; */
		position: relative;
		height: 80vh;
		/* width: 80vw; */
	}

	.btns {

		width: 70px;
		height: 70px;
		background: #0f3854;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		border: 1px solid #0aafe6;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 50%;
		color: #0aafe6;
		text-shadow: 0 0 20px #0aafe6, 0 0 20px rgba(10, 175, 230, 0);
	}

	.stop {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translateX(-50%) translateY(-50%);
	}

	.lup {
		position: absolute;
		top: 0;
		left: 0;
	}

	.rup {
		position: absolute;
		top: 0;
		right: 0;
	}

	.up {
		position: absolute;
		top: 0;
		left: 50%;
		transform: translateX(-50%);
	}

	.rdown {
		position: absolute;
		bottom: 0;
		right: 0;
	}

	.ldown {
		position: absolute;
		bottom: 0;
		left: 0;
	}

	.down {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
	}

	.left {
		position: absolute;
		top: 50%;
		left: 0;
		transform: translateY(-50%);
	}

	.right {
		position: absolute;
		top: 50%;
		right: 0;
		transform: translateY(-50%);
	}
</style>
